package com.jhxy.algorithm.majorityelement;

import java.util.Random;

/**
 * Date: 2024/3/10 15:51
 * Author: T_log
 * Description: 随机数处理
 */
public class RandomSolution {


    public int majorityElement(int[] nums) {
        Random r  = new Random();

        for (int i = 0; i < 10; i++) {
            int index = r.nextInt(nums.length);
            if (isMajor(nums, index)) {
                return nums[index];
            }
        }

        return -1;
    }

    private boolean isMajor(int[] nums, int index) {
        int cnt = 0;
        int halfLen = nums.length/2;
        for (int num : nums) {
            if (num == nums[index]) {
                cnt++;
                if (cnt > halfLen) {
                    return true;
                }
            }
        }
        return false;
    }

}
